import { ref, computed, onUnmounted } from 'vue'
import dayjs from 'dayjs'

//封装倒计时函数
export const useCountDown = () => {
  //响应式的事件对象
  let timer = null
  //响应式的事件对象
  const time = ref(0)
  //格式化时间
  const formatTime = computed(() => {
    return dayjs.unix(time.value).format('mm分ss秒')
  })
  //开始倒计时的函数
  const start = (currentTime) => {
    //倒计时逻辑
    //核心逻辑每隔一秒减一
    time.value = currentTime
    timer = setInterval(() => {
      time.value--
    }, 1000)
  }
  // 清除定时器
  onUnmounted(() => {
    timer && clearInterval(timer)
  })
  return {
    formatTime,
    start
  }
}
